package com.zsk.shop.service.yulink;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsk.shop.common.base.BaseResponse;
import com.zsk.shop.common.utils.DateUtils;
import com.zsk.shop.common.utils.ToolUtil;
import com.zsk.shop.entity.ShopUser;
import com.zsk.shop.entity.yulink.LinkShopLogInfo;
import com.zsk.shop.mapper.LinkShopLogInfoMapper;
import com.zsk.shop.service.ShopUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ljh
 * @create 2022/2/22 14:54
 */
@Service
public class LinkShopLogInfoService extends ServiceImpl<LinkShopLogInfoMapper, LinkShopLogInfo> {

    private static final Logger logger = LoggerFactory.getLogger(LinkShopLogInfoService.class);

    @Resource
    private YlUserService ylUserService;

    @Resource
    private ShopUserService shopUserService;

    /**
     * 增加记录
     *
     * @param phone
     * @return
     */
    public BaseResponse checkLogInfo(String phone) {
        ShopUser user = shopUserService.queryTrueUserByPhone(phone);
        Date time = new Date();
        if (ToolUtil.isEmpty(user)) {
            //设置记录留存
            LinkShopLogInfo infoByPhone = queryInfoByPhone(phone, time);
            if (ToolUtil.isEmpty(infoByPhone)) {
                LinkShopLogInfo infoBak = LinkShopLogInfo.builder().userNo("")
                        .phone(phone).haveTenOrSubUser(1).isHandle(false).createTime(time).build();
                this.save(infoBak);
            }
            return BaseResponse.success();
        }
        //开会满足10分钟
        LinkShopLogInfo info = queryInfoByUserNo(user.getUserNo(), time);
        if (ToolUtil.isEmpty(info)) {
            info = LinkShopLogInfo.builder().userNo(user.getUserNo())
                    .phone(phone).haveTenOrSubUser(1).isHandle(false).createTime(time).build();
            this.save(info);
        } else {
            //已经有满足记录
            if (info.getHaveTenOrSubUser() == 1) {
                //查询我的下级是否有两个用户满足开会(通过定时任务查询)
//                Boolean haveTwoInfo = foundMineSubUserHaveInfo(user, time);
//                if (haveTwoInfo) {
//                    info.setHaveTenOrSubUser(2);
//                    info.setUpdateTime(new Date());
//                    saveOrUpdate(info);
//                }
                //查询上级,用户的下级是否有2个用户开会(通过定时任务查询)
            }
        }
        return BaseResponse.success("添加数据完成");
    }

    public Boolean foundMineSubUserHaveInfo(ShopUser shopUser, Date day) {
        if (ToolUtil.isEmpty(shopUser)) {
            return false;
        }
        List<ShopUser> shopUserList = shopUserService.subShopUserByParentUserNo(shopUser.getUserNo());
        if (ToolUtil.isEmpty(shopUserList)) {
            return false;
        }
        List<String> userNos = shopUserList.stream().map(ShopUser::getUserNo).collect(Collectors.toList());
        if (ToolUtil.isEmpty(userNos)) {
            return false;
        }
        LambdaQueryWrapper<LinkShopLogInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(LinkShopLogInfo::getUserNo, userNos);
        queryWrapper.ge(LinkShopLogInfo::getCreateTime, DateUtils.getDateStart(day));
        queryWrapper.le(LinkShopLogInfo::getCreateTime, DateUtils.getDateEnd(day));
        if (list(queryWrapper).size() >= 2) {
            return true;
        } else {
            return false;
        }
    }

    private LinkShopLogInfo queryInfoByUserNo(String userNo, Date day) {
        LambdaQueryWrapper<LinkShopLogInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LinkShopLogInfo::getUserNo, userNo);
        queryWrapper.le(LinkShopLogInfo::getCreateTime, DateUtils.getDateEnd(day));
        queryWrapper.ge(LinkShopLogInfo::getCreateTime, DateUtils.getDateStart(day));
        queryWrapper.last("limit 1");
        return getOne(queryWrapper);
    }
    
    private LinkShopLogInfo queryInfoByPhone(String phone, Date day) {
        LambdaQueryWrapper<LinkShopLogInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LinkShopLogInfo::getPhone, phone);
        queryWrapper.le(LinkShopLogInfo::getCreateTime, DateUtils.getDateEnd(day));
        queryWrapper.ge(LinkShopLogInfo::getCreateTime, DateUtils.getDateStart(day));
        queryWrapper.last("limit 1");
        return getOne(queryWrapper);
    }

    public void handleLinkShopLogInfoSubUser(Date day) {
        LambdaQueryWrapper<LinkShopLogInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LinkShopLogInfo::getHaveTenOrSubUser, 1);
        queryWrapper.eq(LinkShopLogInfo::getIsHandle, false);
        queryWrapper.le(LinkShopLogInfo::getCreateTime, DateUtils.getDateEnd(day));
        queryWrapper.ge(LinkShopLogInfo::getCreateTime, DateUtils.getDateStart(day));
        List<LinkShopLogInfo> linkShopLogInfoList = list(queryWrapper);
        if (ToolUtil.isEmpty(linkShopLogInfoList)) {
            return;
        }
        List<String> phones = linkShopLogInfoList.stream().map(LinkShopLogInfo::getPhone).collect(Collectors.toList());
        List<ShopUser> shopUserList = shopUserService.listByPhones(phones);
        for (LinkShopLogInfo info : linkShopLogInfoList) {
            ShopUser shopUser = shopUserList.stream().filter(x -> x.getPhone().equals(info.getPhone())).findFirst().orElse(null);
            if (ToolUtil.isEmpty(shopUser)) {
                continue;
            }
            Boolean haveTwoInfo = foundMineSubUserHaveInfo(shopUser, day);
            if (haveTwoInfo) {
                info.setHaveTenOrSubUser(2);
            }
            info.setUpdateTime(new Date());
            saveOrUpdate(info);
        }
    }
}
